package modules::cuffmerge;

sub new {
  my ($class,$config,$fastq_files) = @_;

  my $self = {
               _path             => $config->{'PATH'      },
               _job_name         => $config->{'JOB_NAME'  },
               _gtf_file         => $config->{'GTF_FILE'  },
               _genome           => $config->{'GENOME'    },
               _samples          => $config->{'SAMPLES'   },
             };
  bless $self,$class;
  return $self;
}

sub prepare {
  
  my ($self,$cufflinks_out) = @_;
  my $path                  = $self->{'_path'       };
  my $job_name              = $self->{'_job_name'   };
  my $samples               = $self->{'_samples'    };
  my $job_dir               = $path . '/results/' . $job_name;
  my $cuffmerge_dir         = $job_dir . "/Cuffmerge/";
  
  print "Creating directory '$cuffmerge_dir'...\n";
  mkdir  $cuffmerge_dir, 0777 unless(-d $cuffmerge_dir); chmod(0777, $cuffmerge_dir);

   
  my $assemblies            = "$cuffmerge_dir/assemblies.txt";
  $self->{'_assemblies'   } = $assemblies;
  $self->{'_cuffmerge_dir'} = $cuffmerge_dir;

  print "Creating assemblies.txt...\n";
  
  open (FILE, ">$assemblies");
  map {
      print FILE $cufflinks_out. $_->[0] . "/transcripts.gtf\n";
            
  } @$samples;
  close (FILE); 

  return;
}

sub run {
  my ($self)         = @_;
  my $cuffmerge_dir  = $self->{'_cuffmerge_dir'};
  my $gtf_file       = $self->{'_gtf_file'     };
  my $genome         = $self->{'_genome'       };
  my $assemblies     = $self->{'_assemblies'   };

  my $cmd  = qq(bsub -Is -n 12 -R "span[ptile=4] rusage[mem=5000]" /usr/users/ga002/corpasm/workarea/bin/cuffmerge )
           . qq(-g $gtf_file )
           . qq(-o $cuffmerge_dir -s $genome.fa -p 12 )
           . qq($assemblies);
  
  print "\n\nRUNNING COMMAND:\n$cmd\n\n";
  #system($cmd);
  
  my $wait = 1;
  while ($wait == 1) {
    my  @info = qx(bjobs);
    print scalar localtime() . "\n";
    if(my @cufflinks_jobs = grep(/links_/, @info) ) { map{print $_}@cufflinks_jobs; sleep 10 }
    else {$wait = 0}  
  }  
  return;
}
1; 


